//
//  XGMapViewController.m
//  HuanXin
//
//  Created by monkey on 2019/11/25.
//  Copyright © 2019 itcast. All rights reserved.
//
#import <MapKit/MapKit.h>

#import "XGMapViewController.h"

@interface XGMapViewController () <MKMapViewDelegate>

/// mapView
@property (nonatomic,strong) MKMapView *mapView;
/// 定位管理器
@property (nonatomic,strong) CLLocationManager *manager;
/// 发送位置回调
@property (nonatomic,copy) void(^sendCallBack)(CLPlacemark *placemark);
/// 位置信息
@property (nonatomic,strong) CLPlacemark *placemark;
/// 传递的位置信息
@property (nonatomic,assign) CLLocationCoordinate2D locationCoordinate;

@end

@implementation XGMapViewController

#pragma mark - 公开方法

- (instancetype)initWithLongitude:(CLLocationDegrees)longitude latitude:(CLLocationDegrees)latitude
{
    if (self = [super initWithNibName:nil bundle:nil]) {
        _locationCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
    }
    
    return self;
}

- (void)setSendLocationCallBack:(void (^)(CLPlacemark *placemark))callBack
{
    self.sendCallBack = callBack;
}

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    self.view = self.mapView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUpNavigationItem];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 必须使用CLLocationManager进行requestWhenInUseAuthorization地图才能进行定位
    if (_locationCoordinate.latitude != 0 && _locationCoordinate.longitude != 0) {
        // 展示传来的位置信息
        MKCoordinateRegion region = MKCoordinateRegionMake(_locationCoordinate, MKCoordinateSpanMake(0.024725, 0.014720));
        // 添加大头针
        MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
        annotation.coordinate = self->_locationCoordinate;
        [self->_mapView addAnnotation:annotation];
        // 设置地图范围
        [_mapView setRegion:region animated:YES];
    } else {
        // 根据用户位置定位
        [self.manager requestWhenInUseAuthorization];
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    }
}

// 设置导航栏
- (void)setUpNavigationItem
{
    self.navigationItem.title = @"地图";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(goBackAction)];
    if (_locationCoordinate.latitude == 0 && _locationCoordinate.longitude == 0) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendLocationAction)];
    } else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"复原" style:UIBarButtonItemStylePlain target:self action:@selector(resetAction)];
    }
}

- (void)dealloc
{
    DEBUG_Log_Method;
}

#pragma mark - 事件监听

// 退出事件
- (void)goBackAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 发送位置事件
- (void)sendLocationAction
{
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        weakSelf.sendCallBack(weakSelf.placemark);
    }];
}

// 复原
- (void)resetAction
{
    MKCoordinateRegion region = MKCoordinateRegionMake(_locationCoordinate, MKCoordinateSpanMake(0.024725, 0.014720));
    // 设置地图范围
    [_mapView setRegion:region animated:YES];
}

#pragma mark - MKMapViewDelegate

// 更新用户位置信息
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"解析错误\n%@",error);
            return ;
        }
       
        // 设置大头针信息
        CLPlacemark *placemark = placemarks.lastObject;
        userLocation.title = placemark.subLocality;
        userLocation.subtitle = placemark.name;
        self.placemark = placemark;
    }];
}

// 地图范围发生改变时调用
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    // 获取系统缩放比例
    NSLog(@"latitudeDelta: %f longitudeDelta: %f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}

#pragma mark - 懒加载

- (MKMapView *)mapView
{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] init];
        _mapView.mapType = MKMapTypeStandard;
        _mapView.showsScale = YES;
        _mapView.zoomEnabled = YES;
        _mapView.scrollEnabled = YES;
        _mapView.delegate = self;
    }
    
    return _mapView;
}

- (CLLocationManager *)manager
{
    if (_manager == nil) {
        _manager = [[CLLocationManager alloc] init];
        _manager.desiredAccuracy = kCLLocationAccuracyKilometer;
        _manager.distanceFilter = 1000;
    }
    
    return _manager;
}

@end
